package com.example.tcp.reciver;


import com.alibaba.fastjson.JSONObject;
import com.example.common.constant.Constants;
import com.example.proto.MessagePack;
import com.example.tcp.reciver.process.BaseProcess;
import com.example.tcp.reciver.process.ProcessFactory;
import com.example.tcp.utils.MqFactory;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

@Slf4j
public class MessageReciver {   //这个是来专门用来接收消息的


    private static String brokerId;
    private static void startReciverMessage(){
        try{
            Channel channel = MqFactory.getChannel(Constants.RabbitConstants.MessageService2Im+brokerId);
            //    第一个队列名称，第二是是否持久化，后面两个一般都设置为false,最后一个是额外的参数
            channel.queueDeclare(Constants.RabbitConstants.MessageService2Im+brokerId,true,false,false,null);
           // 绑定交换机
            channel.queueBind(Constants.RabbitConstants.MessageService2Im+brokerId,       //根据不同的brokerId来区分聊天的不同
                    Constants.RabbitConstants.MessageService2Im,brokerId);
            channel.basicConsume(Constants.RabbitConstants.MessageService2Im+brokerId,false,new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    try{
                        String msgStr=new String(body);        //消息的本体
                        MessagePack messagePack = JSONObject.parseObject(msgStr, MessagePack.class);  //转化为MessagePack
                        BaseProcess messageProcess = ProcessFactory.getMessageProcess(messagePack.getCommand());
                        messageProcess.process(messagePack);     //进行消息的发送
                        log.info(msgStr);
                        channel.basicAck(envelope.getDeliveryTag(), false);
                    }catch (Exception e){
                        e.printStackTrace();
                        channel.basicNack(envelope.getDeliveryTag(),false,false);
                    }
                }
            });

        }catch (Exception e){

        }
    }


    public static void init(){
        startReciverMessage();
    }

    public static void init(String brokerId){
        if (StringUtils.isBlank(MessageReciver.brokerId)) {
            MessageReciver.brokerId = brokerId;
        }
        startReciverMessage();
    }

}
